<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\Admin;
use app\models\Department;
use yii\data\Pagination;
use yii\helpers\Url;

class SysadminController extends \app\base\Controller
{
    //管理员列表
    public function actionIndex()
    { 
        $model      = new Admin();
        $admin_ses  = Yii::$app->session['admin_info'];
        if ($admin_ses['powers'] == 'all') {
            $admin_list = $model->get_part_admin_list();
        } else {
            $admin_list = $model->get_part_admin_list($admin_ses['department_id']);
        }
        $oth_list   = $model->remove_not_admin_partment($admin_list);
        $admin_html = $model->made_admin_list_html($oth_list);
        return $this->render('index', ['admin_list_html'=>$admin_html]);
    }

    public function actionAdd()
    {
        $admin_ses  = Yii::$app->session['admin_info'];
        if ($admin_ses['powers'] != 'all') { //非管理员不能使用此功能
            $this->sysMsg('警告', '此功能已经停止使用!', $params = ['type' => 'warning', 'links' => [ ['name'=>'返回上一页', 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $model = new Admin();
        if ($model->load(Yii::$app->request->post()) && $model->add_data()) {
            $rtn_url    = Url::toRoute(['sysadmin/']);
            return $this->sysMsg('提示', '管理员添加成功',$params = [ 'type' => 'success', 'links' => [ ['name'=>'返回管理员列表', 'url'=>$rtn_url] ] ]);
        }
        $dpt_mod    = new Department();
        $par_arr    = array(array('id'=>0, 'de_name'=>'请选择部门', 'parent_id'=>0));
        $dpt_list   = $dpt_mod->getDpt_list();
        $par_arr    = array_merge($par_arr,$dpt_list);
        $sel_html   = $dpt_mod->made_select($par_arr);
        return $this->render('add', [
            'model'      => $model,
            'sel_html'   => $sel_html
        ]);
    }

    public function actionUpdate()
    {
        $admin_ses  = Yii::$app->session['admin_info'];
        if ($admin_ses['powers'] != 'all' && $admin_ses['is_owner'] != 1) {
            $this->sysMsg('提示', '只有管理员和部门负责人才可以更改账号!', $params = ['type' => 'error', 'links' => [ ['name'=>'返回上一页', 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $model = new Admin();
        if ($model->load(Yii::$app->request->post()) && $change_info = $model->save_data()) {
            $rtn_url    = Url::toRoute(['sysadmin/']);
            if ($change_info['is_change']) {
                 return $this->sysMsg('提示', '管理员修改成功',$params = [ 'type' => 'success', 'links' => [ ['name'=>'管理员列表', 'url'=>$rtn_url] ] ]);
            } else {
                 return $this->sysMsg('提示', '没有修改任何数据',$params = [ 'type' => 'success', 'links' => [ ['name'=>'管理员列表', 'url'=>$rtn_url] ] ]);
            }
           
        }
        $up_id      = Yii::$app->request->get('up_id');
        $up_id      = intval($up_id);
        if ($up_id == '' || $up_id == 0) {
            $this->sysMsg('提示', '数据有误!', array('type'=>'error'));
        }
        $up_info    = $model->find()->where(['id'=>$up_id])->asArray()->one();
        if (!$up_info) {
            $this->sysMsg('提示', '没有找到对应的管理员数据!', array('type'=>'error'));
        }      
//        \Yii::pr($model);
//        \Yii::pr($up_info);
        
     
        $model->id          = $up_info['id'];
        $model->username    = $up_info['username'];
        $model->is_owner    = $up_info['is_owner'];
        $model->department_id   = $up_info['department_id'];
        $model->real_name   = $up_info['real_name'];
        $dpt_mod    = new Department();
        $par_arr    = array(array('id'=>0, 'de_name'=>'请选择部门', 'parent_id'=>0));
        if ($admin_ses['powers'] == 'all') {
            $dpt_list   = $dpt_mod->getDpt_list();
        } else {
            $dpt_list   = $dpt_mod->getDpt_list($admin_ses['department_id']);
        }
        $par_arr    = array_merge($par_arr,$dpt_list);
        $sel_html   = $dpt_mod->made_select($par_arr, '', 0, $up_info['department_id']);       
            
        return $this->render('update', [
            'model'     => $model,
            'sel_html'   => $sel_html
        ]);
        
    }

    public function actionDel()
    {
        $admin_ses  = Yii::$app->session['admin_info'];
        $rtn_arr    = [];
        if ($admin_ses['powers'] != 'all' && $admin_ses['is_owner'] != 1) {
            $rtn_arr['_state']  = 'error';
            $rtn_arr['_msg']    = '只有管理员和部门负责人才可以删除账号!';
            echo json_encode($rtn_arr);
            exit;
        }
        $model      = new Admin();
        $del_id      = Yii::$app->request->get('del_id');
        $del_id      = intval($del_id);
        if ($del_id == '' || $del_id == 0) {
            $rtn_arr['_state']  = 'error';
            $rtn_arr['_msg']    = '数据有误!';
            echo json_encode($rtn_arr);
            exit;
        }
        $up_info = $model->find()->where(['id'=>$del_id, 'is_del'=>0])->asArray()->one();
        if (!$up_info) {
            $rtn_arr['_state']  = 'error';
            $rtn_arr['_msg']    = '没有找到对应的管理员数据!';
            echo json_encode($rtn_arr);
            exit;
        }
        $dpt_mod    = new Department();
        if ($admin_ses['powers'] == 'all') {
        } else {
            $low_list = $dpt_mod->get_part_low_list($admin_ses['department_id']);
            if (empty($low_list)) {
                $rtn_arr['_state']  = 'error';
                $rtn_arr['_msg']    = '你没有删除此账号的权限!';
                echo json_encode($rtn_arr);
                exit;
            }
            if (!empty($low_list)) {
                $low_admin  = $model->findBySql('select id from admin where department_id in ('.join(',',$low_list).')')->asArray()->all();
                if ($low_admin) {
                    if (!in_array($del_id,$low_admin)) {
                        $rtn_arr['_state']  = 'error';
                        $rtn_arr['_msg']    = '你没有权限,数据有误!';
                        echo json_encode($rtn_arr);
                        exit;
                    }
                } else {
                    $rtn_arr['_state']  = 'error';
                    $rtn_arr['_msg']    = '数据有误!';
                    echo json_encode($rtn_arr);
                    exit;
                }
            }
        }
        $tmp_md = Admin::findOne($del_id);
        $tmp_md->is_del         = 1;
        $tmp_md->department_id  = 0;
        $tmp_md->is_owner       = 0;
        $tmp_md->last_time      = Yii::$app->systime->time();
        $tmp_md->save(false);
        yii::$app->helper->adminlog(
            $del_id, 
            [
                'model' => $tmp_md, 
                'action' => '删除',
            ], 
            'app\models\AdminLog'
        );	
        Admin::made_admin_cache(); //生成管理员缓存
        $rtn_arr['_state']  = 'ok';
        $rtn_arr['_msg']    = '删除成功!';
        echo json_encode($rtn_arr);
        exit;
    }
    
    public function actionLoglist()
    {
        $AdLog      = new \app\models\AdminLog();
        $count      = $AdLog->find()->count();
        $pageSize   = yii::$app->request->getQueryParam('pagesize');
        $pageSize   = empty($pageSize) ? 10 : intval($pageSize);
        $pages      = new Pagination(['totalCount' => $count, 'defaultPageSize' => $pageSize]);
        $logList    = $AdLog->find()->limit($pages->limit)->offset($pages->offset)->orderBy('id desc')->all();
        return $this->render('loglist', ['logs'=>$logList, 'pages'=>$pages]);
    }
    
    public function actionLoginlog()
    {
        $LgLog      = new \app\models\Loginlog();
        $count      = $LgLog->find()->count();
        $pageSize   = yii::$app->request->getQueryParam('pagesize');
        $pageSize   = empty($pageSize) ? 20 : intval($pageSize);
        $pages      = new Pagination(['totalCount' => $count, 'defaultPageSize' => $pageSize]);
        $logList    = $LgLog->find()->limit($pages->limit)->offset($pages->offset)->asArray()->orderBy('id desc')->all();
        $session    = Yii::$app->session;
        $adminArr   = Yii::$app->cache->get('admin_cache_data');
        foreach ($logList as $k => $v) {
            if (isset($adminArr[$v['admin_id']])) {
                $logList[$k]['admin_name']  = $adminArr[$v['admin_id']]['real_name'];
            } else {
                $logList[$k]['admin_name']  = $v['admin_id'];
            }
            $logList[$k]['add_time']   = Yii::$app->systime->date($v['add_time']);
            $logList[$k]['ip']         = long2ip($v['ip']);
        }
        return $this->render('loginlog', ['logs'=>$logList, 'pages'=>$pages]);
    }
}
